package com.guocheng.quartz.meet;

import com.guocheng.quartz.everyday.Job;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class StatusQuartz {

    @Autowired
    private Scheduler scheduler;

    private static Map<Integer, List<JobKey>> quartzJob = new Hashtable<>();

    /**
     * 添加任务
     *
     * @param time   会议时间
     * @param id     会议id
     * @param status 会议状态
     * @return
     */
    public boolean addJob(Date time, Integer id, Integer status) {
        try {
            Date date = new Date();
            if(time.after(date)){
                return false;
            }
            //定时器
            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(id.toString(), status.toString())
                    .startNow()//立即生效
                    .startAt(time)  //开始执行时间
                    .build();

            //任务参数
            JobDataMap data = new JobDataMap();
            data.put("id", id);
            data.put("status", status);

            //任务
            JobDetail job = JobBuilder.newJob(Job.class)
                    .withIdentity(id.toString(), status.toString())
                    .usingJobData(data)
                    .build();

            //存储任务队列
            List<JobKey> jobKeys = quartzJob.get(id);
            if (jobKeys == null) jobKeys = new ArrayList<>();
            jobKeys.add(job.getKey());
            quartzJob.put(id, jobKeys);

            //将任务添加至调度器中执行
            scheduler.scheduleJob(job, trigger);
        } catch (SchedulerException e) {
            throw new RuntimeException("添加定时任务失败" + e);
        }
        return true;
    }

    /**
     * 添加任务
     *
     * @param start 会议开始时间
     * @param end   会议结束时间
     * @param id    会议id
     * @return
     */
    public boolean addJob(Date start, Date end, Integer id) {
        //添加会议开始定时器
        boolean b = addJob(start, id, 2);
        //添加会议结束定时器
        boolean b1 = addJob(end, id, -1);

        return true;
    }

    /**
     * 根据id删除会议定时任务
     * @param id
     * @return
     */
    public boolean deleteJob(Integer id) {
        try {
            return scheduler.deleteJobs(quartzJob.remove(id));
        } catch (SchedulerException e) {
           return false;
        }
    }

    /**
     * 根据id删除会议定时任务列表中数据（会议结束时删除）
     * @param id
     * @return
     */
    public List<JobKey> deleteJobKey(Integer id) {
        return quartzJob.remove(id);
    }

    /**
     * 修改会议签到定时器
     *
     * @param start
     * @param end
     * @param id
     * @return
     */
    public boolean updateJob(Date start, Date end, Integer id){
        if(deleteJob(id)){
            return addJob(start,end,id);
        }
        return false;
    }

}
